//
//  JZReleaseCourseViewController.m
//  jz_sanrenxing
//
//  Created by GuJun on 16/10/8.
//  Copyright © 2016年 杭州景忠网络科技有限公司. All rights reserved.
//

#import "JZReleaseCourseViewController.h"
#import "JZCourseConditionsTableViewCell.h"
#import "JZDropDownMenu.h"
#import "SZCalendarPicker.h"
#import "ImageSelectManager.h"
#import <UIImageView+WebCache.h>
#import "JZCurrentUserModel.h"
#import "UserInfoTableView.h"

@interface JZReleaseCourseViewController ()<UITableViewDelegate,UITableViewDataSource,JZDropDownMenuDelegate,ImageSelectDelegate,UITextFieldDelegate,UserInfoTableViewDelegate>{
    NSInteger  type;//0 免费   1 收费   2 众筹
    NSString *_imagePath;
    UITextField *_cellTextField;
}

@property (weak, nonatomic) IBOutlet UserInfoTableView *courseTableview;

@property (strong, nonatomic) IBOutlet UIView *courseHeadview;

@property (strong, nonatomic) IBOutlet UIView *courseFootview;

@property (weak, nonatomic) IBOutlet JZDropDownMenu *downMenu;

@property (weak, nonatomic) IBOutlet UILabel *courseNature;

@property (nonatomic, strong) NSArray        *menuArray;

@property (nonatomic, strong) NSArray        *conditionsArray;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *moneyViewHeight;

@property (weak, nonatomic) IBOutlet UILabel *saleMoneyLabel;

@property (weak, nonatomic) IBOutlet UIButton *CourseButton;

@property (weak, nonatomic) IBOutlet UITextField *openCourseTextfield;

@property (weak, nonatomic) IBOutlet UITextField *stopCourseTextfield;

@property (weak, nonatomic) IBOutlet UITextField *moneyCourseTextfield;

@property (weak, nonatomic) IBOutlet UITextField *courseNameTextfield;

@property (weak, nonatomic) IBOutlet UITextField *courseKeywordTextfield;

@property (weak, nonatomic) IBOutlet UITextField *courseIntroTextfield;

@property (weak, nonatomic) IBOutlet UITextField *courseNumTextfield;

@property (weak, nonatomic) IBOutlet UIImageView *courseHomePageImageView;

@property (strong, nonatomic) ImageSelectManager *imageSelectManager;

@property (nonatomic, strong) NSMutableDictionary  *diccc;

- (IBAction)courseButtonClick:(UIButton *)sender;


- (IBAction)CourseDateClick:(UIButton *)sender;

@end

@implementation JZReleaseCourseViewController

- (NSArray *)menuArray{
    
    if (!_menuArray) {
        _menuArray = [NSArray arrayWithObjects:@"免费",@"收费",@"众筹", nil];
    }
    return _menuArray;
    
}

- (NSArray *)conditionsArray{
    
    if (!_conditionsArray) {
        _conditionsArray = [NSArray arrayWithObjects:@"支持人数",@"众筹金额", nil];
    }
    return _conditionsArray;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];

    //存储tableview的textfield的text的字典
    self.diccc = [NSMutableDictionary dictionary];
    
    [self setTingUIandData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setTingUIandData{
    
    self.navigationItem.title = @"发布课程";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.courseTableview.tableHeaderView = self.courseHeadview;
    
    self.courseTableview.tableFooterView = self.courseFootview;
    
    self.courseTableview.separatorStyle  = UITableViewCellSeparatorStyleNone;
    
    self.courseTableview.touchDelegate = self;
    
    self.downMenu.delegate = self;
    
    [self.downMenu setListArray:self.menuArray];
    
    self.moneyViewHeight.constant = 0.0001;
    self.saleMoneyLabel.hidden = YES;
    self.moneyCourseTextfield.hidden = YES;

    [self.CourseButton setTitle:self.butTyle forState:UIControlStateNormal];
        
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addImage)];
    
    [_courseHomePageImageView addGestureRecognizer:tap];
    
    _imageSelectManager = [[ImageSelectManager alloc] init];
    _imageSelectManager.delegate = self;

}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (type == 2) {
        return 2;
    }else{
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (type == 2) {
        JZCourseConditionsTableViewCell *cell = [JZCourseConditionsTableViewCell TableViewCellWithTableView:tableView];
        cell.title.text = self.conditionsArray[indexPath.row];

        _cellTextField = cell.textfield;
        
        cell.textfield.delegate = self;
        
        cell.textfield.tag = indexPath.row;
        
        
        [cell.textfield addTarget:self action:@selector(textFiled:) forControlEvents:UIControlEventAllEditingEvents];
        
        cell.textfield.text = _diccc[[NSString stringWithFormat:@"value%ld", (long)cell.textfield.tag]];
        
        
        return cell;

    }else{
        JZCourseConditionsTableViewCell *cell = [JZCourseConditionsTableViewCell TableViewCellWithTableView:tableView];
        cell.title.hidden = YES;
        cell.textfield.hidden = YES;
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (type == 2) {
        return 44;
    }else{
        return 5;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//保存cell数据
 - (void)textFiled:(UITextField*)field {
    
    [_diccc setObject:field.text forKey:[NSString stringWithFormat:@"value%ld", (long)field.tag]];;
    
}

#pragma mark - JZDropDownMenuDelegate
- (void)selectIndex:(NSInteger)index AtDMDropDownMenu:(JZDropDownMenu *)jzDropDownMenu
{
    NSLog(@"dropDownMenu:%@ index:%ld",jzDropDownMenu,(long)index);
    
    self.courseNature.text = self.menuArray[index];
    type = index;
    //UI是否有金额项的变更
    switch (index) {
            //收费
        case 1:
           
            self.moneyViewHeight.constant = 40;
            self.saleMoneyLabel.hidden = NO;
            self.moneyCourseTextfield.hidden = NO;
            break;
            //众筹和免费
        default:
            
            self.moneyViewHeight.constant = 0.0001;
            self.saleMoneyLabel.hidden = YES;
            self.moneyCourseTextfield.hidden = YES;

            break;
    }
    [self.courseTableview reloadData];
}


- (IBAction)courseButtonClick:(UIButton *)sender {
    
    
//    课程性质，1=众筹课，2=直播客，3=线下课，4=定价课，5=免费课
    NSString *courseType;
    double    coursePay;
    if ([self.courseNature.text isEqualToString:@"免费"]) {
        courseType = @"5";
        coursePay  = 0;
    }else if ([self.courseNature.text isEqualToString:@"收费"]){
        courseType = @"4";
        coursePay  = [self.moneyCourseTextfield.text doubleValue];
    }else if ([self.courseNature.text isEqualToString:@"众筹"]){
        courseType = @"1";
        coursePay  = [[_diccc objectForKey:@"value1"] doubleValue];
    }else{
        courseType = @"2";
    }
    
    
    
    NSURL *fileUrl;
    if (_imagePath) {
        fileUrl = [NSURL fileURLWithPath:_imagePath];
    }

    [HttpUtils requestToAddCourseWithCourse_name:self.courseNameTextfield.text
                                    course_brief:self.courseIntroTextfield.text
                                  course_keyword:self.courseKeywordTextfield.text
                                     coverAvatar:fileUrl
                                 course_property:courseType
                                      course_pay:coursePay
                                 course_part_num:[self.courseNumTextfield.text intValue]
                                    course_bdate:self.openCourseTextfield.text
                                    course_edate:self.stopCourseTextfield.text
                                     course_time:@""
                                          is_hot:@"1"
                                    is_recommend:@"1"
                         crowdfunding_target_num:[[_diccc objectForKey:@"value0"] intValue]
                       crowdfunding_target_money:[[_diccc objectForKey:@"value1"] doubleValue]
                                        callback:^(int code, NSDictionary *dict, NSString *msg) {
                                            
                                            if (1 == code) {
                                                
                                                [SVProgressHUD showInfoWithStatus:msg];
                                    
                                                [self.navigationController popViewControllerAnimated:YES];
                                            } else {
                                                [SVProgressHUD showInfoWithStatus:msg];
                                            }

                                        }];
}

- (IBAction)CourseDateClick:(UIButton *)sender {
    
    SZCalendarPicker *calendarPicker = [SZCalendarPicker showOnView:self.view];
    calendarPicker.today = [NSDate date];
    calendarPicker.date = calendarPicker.today;
    calendarPicker.frame = CGRectMake(0, 100, self.view.frame.size.width, 352);
    calendarPicker.calendarBlock = ^(NSInteger day, NSInteger month, NSInteger year){
        
        NSLog(@"%li-%li-%li", (long)year,(long)month,(long)day);
        
        if (sender.tag == 1000) {
            self.openCourseTextfield.text = [NSString stringWithFormat:@"%li-%li-%li",(long)year,(long)month,(long)day];
        }else{
            self.stopCourseTextfield.text = [NSString stringWithFormat:@"%li-%li-%li",(long)year,(long)month,(long)day];

        }
        
    };

    
    
}

#pragma mark ImageSelectDelegate
- (void)selectedImage:(UIImage *)image FullPath:(NSString *)fullPath{
    if (!image) { return; }
    
    _imagePath = fullPath;
    _courseHomePageImageView.image = [UIImage imageWithContentsOfFile:fullPath];
}


- (void)addImage{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"上传图片" message:@"请选择以下方式添加图片" preferredStyle:UIAlertControllerStyleActionSheet];
    
    __weak typeof(self) weakSelf = self;
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.imageSelectManager pickImageFromCamera:YES];
    }];
    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.imageSelectManager pickImageFromAlbum:YES];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [controller addAction:cameraAction];
    [controller addAction:albumAction];
    [controller addAction:cancelAction];
    
    [self presentViewController:controller animated:YES completion:^{
    }];
}

- (void)touchTableView {
    [_cellTextField resignFirstResponder];
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
